from typing import List
from utils.JSON的输入和输出 import 写入json
'''
使用indx对desc进行分割
'''

file_names = ['WORD_Text', 'WORD_Indx']


# Name Desc 的 start 分别是 0 4
def 渐进处理(start):

    # 读取二进制indx
    with open(f'output/2_res/WORD_Indx.txt', "rb") as f:
        hex_str_list = ("{:02X}".format(int(c))
                        for c in f.read())  # 定义变量接受文件内容
    dec_list = [int(s, 16) for s in hex_str_list]  # 将十六进制转换为十进制

    # 拿到desc的indx
    indx = []
    for i in range(start, len(dec_list), 4):
        tmp = []
        for j in range(4):
            tmp.append(dec_list[i + j])
        indx.append(tmp)

    def fourToOne(x: List[int]) -> int:
        res = 0
        for i in range(3, -1, -1):
            res *= 16 * 16
            res += x[i]
        return res

    indx = [fourToOne(i) for i in indx]
    indx = indx[1:]
    '''
    将2_res的CARD文件转换为JSON文件
    '''

    def solve(data: bytes, desc_indx: List[int]):
        res = []
        for i in range(len(desc_indx) - 1):
            s = data[desc_indx[i]:desc_indx[i + 1]]
            s = s.decode('UTF-8')
            while len(s) > 0 and s[-1] == '\u0000':
                s = s[:-1]
            res.append(s)
        return res

    # 读desc文件进来

    with open("output/2_res/WORD_Text.txt", 'rb') as f:
        data = f.read()

    desc = solve(data, indx)

    写入json(desc, "output/3_res/WORD_Text.json")


if __name__ == '__main__':
    渐进处理(0)
